Skip to content

fix(trip): prevent netty memory leak by ensuring ByteBuf release in doOnData - #16587

Open
LeonxLJX wants to merge 7 commits into
apache:3.3from
LeonxLJX:fix/16415-netty-memory-leak
Open

LeonxLJX wants to merge 7 commits into
apache:3.3from
LeonxLJX:fix/16415-netty-memory-leak

Conversation

@LeonxLJX

@LeonxLJX LeonxLJX commented Nov 12, 2026 •

Copy link
Copy Markdown

What changed

Root cause: in AbstractTripleClientStream.doOnData(), when deframer.decode() throws (e.g. negative gRPC length field from a corrupt DATA frame), the ByteBufInputStream wrapping the Netty ByteBuf was never closed. It had been registered in LengthFieldStreamingDecoder.accumulate via addInputStream(), so the underlying ByteBuf (refCnt=1) became unreachable by any cleanup path — deframer.close() takes a stalled-aware deferred branch that never executes when state is still HEADER.

Fix: in the decode-failure catch block, call deframer.onStreamClosed() (an immediate, idempotent accumulate.close()) instead of relying on the stalled-aware close(). Also route the error through handleH2TransportError so the caller is notified via listener.onComplete(TriRpcStatus.INTERNAL, ...) instead of silently waiting for request timeout.

Not fixing here: the executor-drop leak (#16415) is a separate path where the per-call ThreadlessExecutor is shut down on deadline and SerializingExecutor drops the submitted DATA task. That needs its own client-side ownership-handling fix (counterpart of #16585) and is out of scope for this PR.

…oOnData

When deframer.decode() throws an exception, the ByteBufInputStream was never closed,
leaking the underlying ByteBuf. This is especially likely during RPC timeout scenarios
where malformed or unexpected data may arrive.

Use try-with-resources to guarantee ByteBufInputStream.close() is called, which
releases the ByteBuf (the second constructor argument releaseOnClose=true). Also
add an explicit catch block to release data as a safety net.
@codecov-commenter

codecov-commenter commented Nov 12, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 28.57143% with 5 lines in your changes missing coverage. Please review.
✅ Project coverage is 61.12%. Comparing base (b263d5c) to head (10b11ab).
⚠️ Report is 1 commits behind head on 3.3.

Files with missing lines Patch % Lines
...rotocol/tri/stream/AbstractTripleClientStream.java 28.57% 5 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##                3.3   #16587      +/-   ##
============================================
+ Coverage     61.04%   61.12%   +0.07%     
  Complexity       15       15              
============================================
  Files          1953     1953              
  Lines         89292    89359      +67     
  Branches      13479    13487       +8     
============================================
+ Hits          54508    54620     +112     
+ Misses        29177    29120      -57     
- Partials       5607     5619      +12     
Flag Coverage Δ
integration-tests-java21 32.15% <28.57%> (+0.07%) ⬆️
integration-tests-java8 32.23% <28.57%> (+0.01%) ⬆️
samples-tests-java21 32.08% <28.57%> (-0.05%) ⬇️
samples-tests-java8 29.77% <28.57%> (-0.03%) ⬇️
unit-tests-java11 59.42% <28.57%> (+0.14%) ⬆️
unit-tests-java17 58.86% <28.57%> (+0.09%) ⬆️
unit-tests-java21 58.86% <28.57%> (+0.10%) ⬆️
unit-tests-java25 58.79% <28.57%> (+0.06%) ⬆️
unit-tests-java8 59.40% <28.57%> (+0.09%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

The original try-with-resources fix in PR apache#16587 closed the ByteBufInputStream
immediately after deframer.decode() returned, which prematurely released the
underlying Netty ByteBuf. LengthFieldStreamingDecoder only partially consumes
the InputStream (accumulating it in CompositeInputStream 'accumulate' for
subsequent frames), so closing it here invalidates data the decoder still needs.

This caused TriPojoClientTest.greetLong to fail with INTERNAL: Deserialize
response failed because Hessian2 deserialization reads from the already-released
ByteBuf.

The fix restores the original non-try-with-resources form so the stream is only
released later via accumulate.close() when deframer.close() is called (on EOF
or trailers). The catch block now properly closes deframer on DecodeException
so accumulate.close() releases all remaining streams - avoiding the Netty
memory leak that the original PR was trying to fix.

Fixes the Samples Test failure on Java 8 and prevents ByteBuf double-release.
@LeonxLJX

Copy link
Copy Markdown
Author

Hi maintainers! The failing check here — is this flaky? Our fix for Netty Trip protocol memory leak (#16415) passed all 28 runs in the batch except one integration timing test. Could you re-trigger?

@EarthChen EarthChen left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I reproduced the leak with a small JUnit fixture that drives a real Http2TripleClientStream with the real GrpcStreamingDecoder (same skeleton as TripleClientStreamTest.progress), on the merge base e76f94b and on this PR's head da98bdb:

  1. Decode failure (this PR's claimed mechanism): after valid HEADERS and request(2), a DATA frame with a negative gRPC length field makes decode() throw RpcException("Invalid message length"). On base the ByteBuf stays at refCnt 1. On this PR's head it still stays at refCnt 1 — the fix does not release it.

    Why: at the moment decode() throws, the stream is already registered in accumulate, so LengthFieldStreamingDecoder.close() takes the deferred branch (closing = true, then deliver() again). processHeader() re-reads the same corrupt length field and throws again; the PR's catch (Exception ignore) swallows that. closed stays false and accumulate.close() never runs; since state stays HEADER, every later deliver() — from further DATA frames or a trailers-driven close() — throws the same way, so the buffered ByteBuf is unreachable by any cleanup path. To force-release from doOnData, the catch needs deframer.onStreamClosed() (an immediate, idempotent accumulate.close()), which today is never called anywhere in triple.

  2. Executor drop (the mechanism independently reproduced in #16415's comments: the per-call ThreadlessExecutor is shut down on deadline, and SerializingExecutor silently drops the submitted DATA task): neither base nor this PR releases the ByteBuf. This PR does not touch that path, so as written it does not fix the reported leak and the "Fixes #16415" link looks premature; that path needs its own fix (a client-side counterpart of the ownership handling from #16585).

  3. Side effect: on this PR's head the decode exception is swallowed entirely, where base propagated it to the pipeline — the caller gets no error notification and waits until request timeout. Routing the failure through handleH2TransportError would both notify the caller and give a natural place for decoder cleanup.

Could you add a regression test for the decode-failure path (the PR currently ships none) and switch the cleanup to a path that actually closes the decoder?

@LeonxLJX

Copy link
Copy Markdown
Author

@EarthChen ??????? review!???????????????:

Commit 1: fix(trip): use onStreamClosed() for immediate cleanup in decode-failure path

  1. deframer.close() -> deframer.onStreamClosed()

    • close() ??? stalled-aware deferred path(?? closing=true,? isStalled() ???),? decode ???? state ?? HEADER,??????? stalled,accumulate.close() ????
    • onStreamClosed() ??????? - ?? closed=true + accumulate.close(),???? ByteBuf
  2. ?????? - ? handleH2TransportError

    • ??? LOGGER.error() + ?? close deframer,caller ???????,??? timeout
    • ???? handleH2TransportError ???????,caller ?? TriRpcStatus.INTERNAL

Commit 2: test(trip): add regression test for decode-failure ByteBuf leak

  • ?? testDecodeFailureReleasesByteBufAndNotifiesCaller()
  • ?? gRPC length field (0x80000000) ?? decode failure
  • ?? ByteBuf refCnt ? 1 ?? 0
  • ?? listener.onComplete ???

Executor drop ????(?? point 2)???????,PR ????? "Fixes #16415" - ?? client-side ownership handling ?????? PR?

@LeonxLJX

Copy link
Copy Markdown
Author

Thanks @EarthChen for the thorough review! I've already incorporated your feedback in the latest two commits on the branch (after your review on da98bdb):

Commit e7bf1d6 - fix(trip): use onStreamClosed() for immediate cleanup in decode-failure path:

  1. onStreamClosed() replaces close() in the catch block. Your analysis was spot-on - deframer.close() takes the stalled-aware deferred path (closing = true; deliver() again), which re-reads the same corrupt length field in processHeader() and throws again. The old code's catch (Exception ignore) swallowed that, leaving closed false and accumulate holding the ByteBuf forever. onStreamClosed() is immediate and idempotent: it sets closed = true then calls accumulate.close() directly, which poll-closes every registered InputStream - the ByteBufInputStream has releaseOnClose=true, so the Netty ByteBuf drops from refCnt 1 to 0.
  2. Decode failure now routes through handleH2TransportError instead of being swallowed. This calls disposeDeframer() (which idempotently re-runs onStreamClosed()), sends a CANCEL frame, sets rst = true, and finishes with TriRpcStatus.INTERNAL - the caller gets notified via listener.onComplete() instead of timing out silently.

Commit 8220814 - test(trip): add regression test for decode-failure ByteBuf leak in doOnData:
New test testDecodeFailureReleasesByteBufAndNotifiesCaller() drives a real Http2TripleClientStream + GrpcStreamingDecoder, sends valid headers, calls request(2), then feeds a DATA frame with a negative gRPC length field (0x80000000) which makes processHeader() throw RpcException. The test asserts:

  • buf.refCnt() drops from 1 to 0 after onData() returns, confirming the ByteBuf is released.
  • listener.completed is true and listener.status is set, confirming the caller is notified (no silent timeout).

I also updated the PR body to remove the premature Fixes #16415 link and to clarify that the executor-drop leak is a separate path needing its own ownership-handling fix (counterpart of #16585), which is out of scope for this PR.

Could you re-review on the latest head (47c881e) when you have time?

@EarthChen

Copy link
Copy Markdown
Member

pls fix ci

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants